package com.order.system.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import com.order.system.common.result.ServiceResult;
import com.order.system.gateway.common.constant.FilterOrder;
import com.order.system.gateway.common.constant.FilterType;
import com.order.system.gateway.model.UserInfo;
import com.order.system.gateway.service.CacheHystrixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Optional;

/**
 * 登陆拦截过滤器
 *
 * @author zhongh2
 */
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    CacheHystrixService cacheHystrixService;

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public Object run() {
        log.info("start LoginFilter ---");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
//        String loginSecret = request.getHeader("loginSecret"); // 登陆密钥放在请求头里面
        String loginSecret = "eVwIPRL9";
        Optional.ofNullable(loginSecret).ifPresent((String v) -> {
            ServiceResult loginInfoResult = cacheHystrixService.getLoginInfo(loginSecret);
            Optional.ofNullable(loginInfoResult).filter(x -> "200".equals(x.getCode().toString())).ifPresent((ServiceResult j) -> {
                //make loginInfo push requestBody
                try {
                    UserInfo userInfo = mapper.readValue(JSON.toJSONString(j.getData()), UserInfo.class);
                    System.out.println("登录用户信息为：" + JSON.toJSONString(userInfo));
                    //InputStream in = ctx.getRequest().getInputStream();

                    JSONObject json = JSON.parseObject(JSON.toJSONString(userInfo));

                    //Map<String, String[]> parameterMap = request.getParameterMap();

                    json.put("test","test1");

                    String newBody = json.toString();

                    System.out.println("newBody:" + newBody);
                    final byte[] reqBodyBytes = newBody.getBytes();
                    ctx.setRequest(new HttpServletRequestWrapper(request) {
                        @Override
                        public ServletInputStream getInputStream() throws IOException {
                            return new ServletInputStreamWrapper(reqBodyBytes);
                        }

                        @Override
                        public int getContentLength() {
                            return reqBodyBytes.length;
                        }

                        @Override
                        public long getContentLengthLong() {
                            return reqBodyBytes.length;
                        }

                        @Override
                        public String getHeader(String name) {
                            return "Content-type: application/json";
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        });
        log.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
        return null;
    }

    /**
     * shouldFilter代表这个过滤器是否生效 true代表生效，false代表不生效
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public int filterOrder() {
        return FilterOrder.SECOND;
    }

    @Override
    public String filterType() {
        return FilterType.PRE;
    }

}
